//
//  AppDelegate+JPush.m
//  MobileOffice
//
//  Created by jjkj on 17/3/1.
//  Copyright © 2017年 liaoningjujin. All rights reserved.
//

#import "AppDelegate+JPush.h"
#import "LoginApIModel.h"
//ios10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
static NSString *channel = @"Publish channel";
static BOOL isProduction = FALSE;

@implementation AppDelegate (JPush)

-(void)setUpJPushWithLaunchOption:(NSDictionary *)options
{
    //初始化APNs
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc]init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    //可以添加自定义categories
    if (IOS_VERSION_10_OR_LATER) {
        NSSet<UNNotificationCategory *> *categories;
        entity.categories = categories;
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (!error) {
                NSLog(@"request authorization succeeded!");
            }
        }];

    }
    else {
        NSSet<UIUserNotificationCategory *> *categories;
        entity.categories = categories;
    }
    
    
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];

    //初始化JPUSH
    //如不需要使用IDFA，advertisingIdentifier 可为nil
    [JPUSHService setupWithOption:options appKey:JGAPPKEY
                          channel:channel //指明应用程序下载的渠道
                 apsForProduction:isProduction //用于表示当前应用所使用的APNs证书环境 0指开发证书（默认） 1 生产证书 与Build Settings的Code Signing配置的证书环境一致
            advertisingIdentifier:nil];
    

    [self sendLocalNotification];
}

//获取自定义消息发送本地推送
-(void)sendLocalNotification
{
    //获取消息
    NSNotificationCenter * notCenter = [NSNotificationCenter defaultCenter];
    [notCenter addObserver:self selector:@selector(netWorkdisReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];

}


#pragma mark - JPush 推送回调
//注册APNS成功并上传保存 deviceToken
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    [JPUSHService registerDeviceToken:deviceToken];
}
//注册APNS注册失败回调
- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}


- (void)application:(UIApplication *)application
didRegisterUserNotificationSettings:
(UIUserNotificationSettings *)notificationSettings {
}

// Called when your app has been activated by the user selecting an action from
// a local notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application
handleActionWithIdentifier:(NSString *)identifier
forLocalNotification:(UILocalNotification *)notification
  completionHandler:(void (^)())completionHandler {
}
#pragma mark - JPush delegate
//处理APNs通知回调方法
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    NSDictionary * userInfo = notification.request.content.userInfo;
    
    UNNotificationRequest *request = notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        //        NSLog(@"iOS10 前台收到远程通知:%@", [self logDic:userInfo]);
        
        
        
    }
    else {
        // 判断为本地通知
        NSLog(@"iOS10 前台收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
        self.userInfos = userInfo;
        if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
            [self locationNotShowAlert:body];
        }else{
            [self goViewController];
        }
    }
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
}

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    UNNotificationRequest *request = response.notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        //        NSLog(@"iOS10 收到远程通知:%@", [self logDic:userInfo]);
        
        
    }
    else {
        // 判断为本地通知
        NSLog(@"iOS10 收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
        self.userInfos = userInfo;
        if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
            [self locationNotShowAlert:body];
        }else{
            [self goViewController];
        }
    }
    
    completionHandler();  // 系统要求执行这个方法
}
#endif
//ios7以上
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
 
}
//iOS6及以下系统
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
    [JPUSHService handleRemoteNotification:userInfo];
}
//本地推送
- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
//    [JPUSHService showLocalNotificationAtFront:notification identifierKey:nil];
    
    if ([UIApplication sharedApplication].applicationIconBadgeNumber > 0) {
        [UIApplication sharedApplication].applicationIconBadgeNumber = [UIApplication sharedApplication].applicationIconBadgeNumber-1;
    }else{
        [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    }
    self.userInfos = notification.userInfo;
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
       [self locationNotShowAlert:notification.alertBody];
    }else{
        [self goViewController];
    }

    
   
}
#pragma  mark - 极光获取自定义消息
-(void)netWorkdisReceiveMessage:(NSNotification *)messageInfo
{
    NSString *content = [[messageInfo userInfo] valueForKey:@"content"];
    
    NSArray * contentArr = [content componentsSeparatedByString:@"&"];
    //strMessage
    if (contentArr.count > 1) {
        NSString * body = [contentArr objectAtIndex:3];
        self.userInfos = [body mj_JSONObject][@"retContent"];
        //应用内提示，应用外进行本地推送
        if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
            [self showAlertWithTitle:nil content:self.userInfos[@"content"]];
        }else{
            [RootViewController setLocalNotification:self.userInfos[@"content"] userInfo:self.userInfos type:2 date:nil];
            [UIApplication sharedApplication].applicationIconBadgeNumber = [contentArr.lastObject integerValue];
        }
    }else{
//        [self showAlertWithTitle:nil content:contentArr.firstObject];
    }
    
}
/**
 *  应用提示
 *  title 标题 content 内容
 */
-(void)showAlertWithTitle:(NSString *)title content:(NSString *)content
{
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
        // 推送消息的标题 title
        return;
    }
    
    
}
/**
 *  本地推送应用内提示
 *  content 内容  签到签退使用
 */
-(void)locationNotShowAlert:(NSString *)content
{

    
}
#pragma mark - 跳转界面
-(void)goViewController
{

}


@end
